package com.ddc.study.feature.collect.article;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.ddc.study.R;
import com.ddc.study.base.MvpFragment;
import com.ddc.study.entity.Collection;
import com.ddc.study.entity.MainData;
import com.ddc.study.feature.html.HtmlActivity;
import com.ddc.study.view.VerticalDecoration;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.ListPopupWindow;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created on 2018/6/7.
 *
 * @author lshun
 * @version 1.0
 */
public class CollectArticleFragment extends MvpFragment<CollectArticleContract.IView, CollectArticleContract.IPresenter>
        implements CollectArticleContract.IView {
    private static final String RESULT_INTENT_KEY_DATA = "data";

    @BindView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout mSwipeRefreshLayout;

    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;

    private final Adapter mAdapter = new Adapter();
    private int mPage;

    public static Fragment getInstance() {
        return new CollectArticleFragment();
    }

    @Nullable
    public static List<Integer> getUnCollectIdList(@Nullable Intent intent) {
        if (intent == null) return null;
        return intent.getIntegerArrayListExtra(RESULT_INTENT_KEY_DATA);
    }

    @Override
    protected CollectArticleContract.IPresenter createPresenter() {
        return new CollectArticlePresenter();
    }

    @Override
    protected int getLayoutRes() {
        return R.layout.frag_collect_article;
    }

    @Override
    protected void initView() {
        super.initView();
        if (getActivity() == null) return;

        //加载第一页数据
        mPresenter.loadData(1);
        mSwipeRefreshLayout.setRefreshing(true);
        mAdapter.setEnableLoadMore(false);

        mSwipeRefreshLayout.setOnRefreshListener(() -> {
            mPresenter.loadData(1);
            mAdapter.setEnableLoadMore(false);
        });

        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.addItemDecoration(new VerticalDecoration(getActivity()));

        mAdapter.bindToRecyclerView(mRecyclerView);
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            Collection collection = (Collection) adapter.getItem(position);
            if (collection != null && getActivity() != null) {
                HtmlActivity.openUrl(getActivity(), collection.getLink());
            }
        });

        /*TextView tv = new TextView(getActivity());
        tv.setText("无收藏数据");
        tv.setGravity(Gravity.CENTER);
        mAdapter.setEmptyView(tv);*/

        mAdapter.setPreLoadNumber(5);
        mAdapter.setOnLoadMoreListener(() -> {
            mSwipeRefreshLayout.setEnabled(false);
            mPresenter.loadData(mPage + 1);//请求下一页的数据
        }, mRecyclerView);

        mAdapter.setOnItemLongClickListener((adapter, view, position) -> {
            final String[] items = {"删除"};
            final ListPopupWindow listPopupWindow = new ListPopupWindow(getActivity());
            listPopupWindow.setAdapter(new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, items));
            listPopupWindow.setOnItemClickListener((parent, view1, pos, id) -> {
                if (pos == 0) {
                    Collection item = mAdapter.getItem(position);
                    if (item != null) {
                        mPresenter.unCollectArticle(item.getId(), item.getOriginId());
                        listPopupWindow.dismiss();
                    }
                }
            });
            listPopupWindow.setAnchorView(view);
            listPopupWindow.setHorizontalOffset(view.getWidth() / 2);
            listPopupWindow.setWidth(400);
            listPopupWindow.setModal(false);
            listPopupWindow.show();
            return true;
        });
    }

    @OnClick(R.id.fab)
    void addCollect() {
        if (getActivity() == null) return;

        //TODO 用DialogFragment替换
        final View v = View.inflate(getActivity(), R.layout.dialog_add_collect_article, null);

        final AlertDialog dialog = new AlertDialog.Builder(getActivity())
                .setTitle(R.string.add_collect)
                .setView(v)
                .setCancelable(false)
                .setPositiveButton(android.R.string.ok, null)
                .setNegativeButton(android.R.string.cancel, null)
                .show();

        dialog.getButton(DialogInterface.BUTTON_POSITIVE)
                .setOnClickListener(view -> {
                    EditText edtTitle = v.findViewById(R.id.edt_title);
                    EditText edtAuthor = v.findViewById(R.id.edt_author);
                    EditText edtLink = v.findViewById(R.id.edt_link);
                    boolean valid = true;

                    if (edtLink.getText().length() == 0) {
                        edtLink.setBackgroundResource(R.drawable.edt_background_error);
                        edtLink.requestFocus();
                        valid = false;
                    } else {
                        edtLink.setBackgroundResource(R.drawable.edt_background_normal);
                    }

                    if (edtTitle.getText().length() == 0) {
                        edtTitle.setBackgroundResource(R.drawable.edt_background_error);
                        edtTitle.requestFocus();
                        valid = false;
                    } else {
                        edtTitle.setBackgroundResource(R.drawable.edt_background_normal);
                    }

                    if (valid) {
                        dialog.dismiss();
                        String title = edtTitle.getText().toString();
                        String author = edtAuthor.getText().toString();
                        String link = edtLink.getText().toString();
                        mPresenter.addCollect(title, author, link);
                    }
                });
    }

    @Override
    public void loadDataSuccess(MainData<Collection> data) {
        if (mSwipeRefreshLayout.isRefreshing()) {
            mSwipeRefreshLayout.setRefreshing(false);
            mAdapter.setEnableLoadMore(true);//TODO 是否启用还需要判断
            mPage = 1;
            mAdapter.setNewData(data.getData());
            if (data.isDataLoadOver()) {
                mAdapter.loadMoreEnd();
            }
        } else if (mAdapter.isLoading()) {
            mSwipeRefreshLayout.setEnabled(true);
            mPage++;
            mAdapter.addData(data.getData());
            if (data.isDataLoadOver()) {
                mAdapter.loadMoreEnd();
            } else {
                mAdapter.loadMoreComplete();
            }
        }
    }

    @Override
    public void loadDataFailed(String msg) {
        if (mSwipeRefreshLayout.isRefreshing()) {
            mSwipeRefreshLayout.setRefreshing(false);
            mAdapter.setEnableLoadMore(true);

            if (mAdapter.getData().isEmpty()) {
                //recyclerView中无数据展示时提示加载失败
                showToast("加载失败，请重试");
            } else {
                //重新加载数据时失败
                showToast("刷新失败，请稍候重试");
            }
        } else if (mAdapter.isLoading()) {
            mSwipeRefreshLayout.setEnabled(true);
            mAdapter.loadMoreFail();
        }
    }

    private final ArrayList<Integer> mResults = new ArrayList<>();

    @Override
    public void showUnCollectResult(boolean result, int id, int originId) {
        if (!result) return;

        Collection collection;
        for (int i = 0, size = mAdapter.getData().size(); i < size; i++) {
            collection = mAdapter.getItem(i);
            if (collection != null && collection.getId() == id
                    && collection.getOriginId() == originId) {
                mAdapter.remove(i);
                break;
            }
        }

        mResults.add(originId);
        if (getActivity() == null) return;
        Intent i = new Intent();
        i.putIntegerArrayListExtra(RESULT_INTENT_KEY_DATA, mResults);
        getActivity().setResult(Activity.RESULT_OK, i);
    }

    @Override
    public void showAddCollectResult(boolean result) {
        if (result) {
            mPage = 0;
            mPresenter.loadData(mPage);
            mAdapter.setEnableLoadMore(false);
        }
    }

    private static class Adapter extends BaseQuickAdapter<Collection, BaseViewHolder> {
        Adapter() {
            super(R.layout.item_collection, null);
        }

        @Override
        protected void convert(BaseViewHolder helper, Collection item) {
            helper.setText(R.id.tv_content, item.getTitle())
                    .setText(R.id.tv_author, item.getAuthor())
                    .setText(R.id.tv_time, item.getNiceDate());
        }
    }
}
